package cn.wolfcode.wolf2w.exception;

import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一异常处理
 */
@ControllerAdvice
public class UnifedException {

    @ExceptionHandler(LogicalException.class)
    @ResponseBody
    public Object LogicalException(Exception e, HttpServletResponse resp) throws IOException {
        //打印异常信息
        e.printStackTrace();
        //防止中文乱码
        resp.setContentType("application/json;charset=utf-8");
        return JsonResult.error(JsonResult.CODE_ERROR, e.getMessage(), null);
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Object runTimeExp(Exception e, HttpServletResponse resp) throws IOException {
        e.printStackTrace();
        resp.setContentType("application/json;charset=utf-8");
        return JsonResult.defaultError();
    }
}

